// pages/Goods/Address/list/index.js
var common = require("../../../../public.js");
// var QQMapWX = require('../../utils/qqmap-wx-jssdk1.2/qqmap-wx-jssdk.min.js');
const QQMapWX = require('../../../../../libs/qqmap-wx-jssdk1.2/qqmap-wx-jssdk') //腾讯
var qqmapsdk;

Page({
    /**
     * 页面的初始数据
     */
    data: {
        token: '',
        userInfo: {},
        addressList: [],
        from: '', //页面进入
        active: '',
        isLoadingBusy: false,
        paramArr: [],
        addressLists:[]
    },
    /**
     * 生命周期函数--监听页面加载
     */


    onLoad: function (opt) {
        console.log(opt,"来自哪里")
        // JSON.parse(options.params)
        const that = this

        common.getLocalUserInfo(function (success, data) {
            if (success) {
                that.setData({
                    userInfo: data.user,
                    token: data.token,
                    itemId: opt.itemId ? opt.itemId : '',
                    storeId: opt.storeId ? opt.storeId : 1641,
                    from: opt.from ? opt.from : '',
                    storePrice: opt.storePrice ? opt.storePrice : '',
                    active: opt.active ? opt.active : '',
                    params: opt.orderInfo ? JSON.parse(opt.orderInfo) : '',

                }, function () {
                    that.getList()
                    // that.getIsList()
                })
            }
        })

        // that.mapCtx = wx.createMapContext('myMap')
        // 实例化API核心类
        qqmapsdk = new QQMapWX({
            //   key: 'W57BZ-JDB6X-XPA4H-Z76MI-73FF2-24BT4'
            key: 'SUOBZ-SJG6B-PQQUT-JL75Z-3F3Z5-AAFJ3' // 原P35BZ-K2WAS-GUZO7-6IRVW-IYBQV-ZUB6B
        });

    },
    onShow() {
        // this.getList()
    },
    addAddress() { // 添加新地址
        if(this.data.addressLists.length>=5){
          common.showToast('最多可添加5条地址')
          return
        }
        wx.navigateTo({
            url: '/packageA/pages/Goods/Address/addAddress/index?from=0',
        })
    },
    changeAddress(e) { // 修改地址
        // console.log('address',e.currentTarget.dataset.item)
        console.log(e,"4444444")
      
        let item = JSON.stringify(e.currentTarget.dataset.item)
        wx.navigateTo({
            url: '/packageA/pages/Goods/Address/addAddress/index?from=1&item=' + item,
        })
    },


    // 地址列表
    getList() {
        this.setData({
            isLoadingBusy: true
        })
        const that = this
        const param = {
            token: that.data.token,
            userId: that.data.userInfo.id
        }
        if (that.data.addressLists.length > 0) {
            that.setData({
                addressLists: []
            })
        }
        if (that.data.paramArr.length > 0) {
            that.setData({
                paramArr: []
            })
        }

        common.getJson('/user/ship/list', param, function (res) {
            if (res.status === 200) {
                that.setData({
                    addressLists: res.data
                }, () => {
                    res.data.forEach((item, index) => {
                        that.addressAnalysis(item.receiverAddress, index, item)
                      
                    })
                

                })

            }

        },
            function () {
                setTimeout(function () {
                    that.setData({
                        isLoadingBusy: false
                    })
                }, 200);
            })
    },
    addressAnalysis(address, index, item) {
        // return new Promise((resolve, rej) => {
        const that = this
        qqmapsdk.geocoder({
            //获取表单传入地址
            address: address, //地址
            success: function (res) {//成功后的回调
                that.data.paramArr.push({
                    storeId: that.data.storeId,
                    shipId: item.id,
                    xpoint: res.result.location.lng,
                    ypoint: res.result.location.lat
                })
                if(that.data.paramArr.length==that.data.addressLists.length){
                    console.log(that.data.addressLists, "kkkkkkkkkkkkkk")
                    that.getIsList(that.data.paramArr)  //是否可以配送  
                }else{
                    // console.log(that.data.addressLists, "kkkkkkkkkkkkkk")
                }
            },
            fail: function (error) {
                common.showToast(error)
            },
            complete: function (res) {
                // console.log(index,"内")

                // resolve(res.result.location)
            }
        })
        // })
    },
  
    //   验证是否在商家可配送范围
    getIsList(param) {
        const that = this
        this.setData({
            isLoadingBusy: true
        })
        if (that.data.addressList.length > 0) {
            that.setData({
                addressList: []
            })
        }

        common.postJson('/store/getStoreIsDeliveredList', param, function (res) {
            if (res.status === 200) {
                  console.log(res,"pjjjjjjjjjjjjjjjjjj")
                that.setData({
                    addressList: res.data
                },()=>{
                    console.log(that.data.addressList,"ikipppp")
                })
            }
        },
            function () {
                setTimeout(function () {
                    that.setData({
                        isLoadingBusy: false
                    })
                }, 200);
            })
    },


    clickgetId(e) {
        let that = this
        if (e.currentTarget.dataset.deliveredflag == 2 && (this.data.from=='tobepaidCommit' || this.data.from=='goodsCommit')) {
            common.showToast('超出范围')
            return
        }
        if (this.data.from == "mySelf") return;
        var pages = getCurrentPages()
        var prevPage = pages[pages.length - 2] //上一个页面

        if (this.data.from == 'crowdOrder') {
            console.log(that.data.params, "55555")
            const paramss = {
                selectedAddr: true, // false代表已经选择地址
                receiverName: e.currentTarget.dataset.name,
                receiverMobile: e.currentTarget.dataset.phone,
                receiverAddress: e.currentTarget.dataset.address,
                id: e.currentTarget.dataset.id,
                crowdfundingId: this.data.params.crowdfundingId,
                setmeal: this.data.params.setmeal,
                payNum: this.data.params.payNum,
                storeId: this.data.params.storeId,
                storeName: '',
                storeImage: '',

            }
            console.log(paramss, "000000")
            var params = JSON.stringify(paramss)
            wx.navigateBack({
                delta: 1,
                success: function () {
                    prevPage.onLoad(params)
                }
            })
            return
        }
        if(that.data.from == 'tobepaidCommit'){
           
            wx.navigateBack({
                delta: 1,
                success: function () {
                    prevPage.setData({
                        receiverAddress:e.currentTarget.dataset.address
                    })
                    prevPage.data.receiverAddress = e.currentTarget.dataset.address
                }
            })
            return
        }

        const options = {
            // active: 2,
            storeId: that.data.storeId,
            itemId: that.data.itemId,
            selectedAddr: true, // false代表已经选择地址
            receiverName: e.currentTarget.dataset.name,
            receiverMobile: e.currentTarget.dataset.phone,
            receiverAddress: e.currentTarget.dataset.address,
            id: e.currentTarget.dataset.id,
            storePrice: this.data.storePrice
        }

        wx.navigateBack({
            delta: 1,
            success: function () {
                prevPage.onLoad(options)
            }
        })
        // wx.navigateTo({
        //   url: "../Commit/index?active=2&storeId=" + this.data.storeId + '&itemId=' + this.data.itemId + '&receiverName=' + e.currentTarget.dataset.name + '&receiverMobile=' + e.currentTarget.dataset.phone + '&receiverAddress=' + e.currentTarget.dataset.address + '&index1=' + this.data.index1 + '&id=' + e.currentTarget.dataset.id
        // })
    },

    onClose() {
        this.setData({
            rangeShow: false
        })
    },
    onConfirm() {
        console.log('ssss');
        this.setData({
            rangeShow: false
        })
    },
})